<?php
/**
 * 商品
 * User: ws
 * Date: 2018/8/8
 * Time: 11:11
 */

namespace app\admin\controller;
use app\admin\model\Goods as GoodsModel;
use app\admin\model\Label as LabelModel;
use app\admin\model\Materiel as MaterielModel;
use app\admin\model\GoodsLabel as GoodsLabelModel;
use app\admin\model\Coode as CoodeModel;
use app\admin\model\SpecGoodsPrice;
use think\Db;
use think\Config;
class Goods  extends Init
{
    function _initialize()
    {
        parent::_initialize();
        $this->model = model('goods');
        $this->SpecGoodsPrice = model('spec_goods_price');
        $this->goods_label = model('goods_label');
        $this->code = model('code');
        $this->store = model('store');
    }
    function index(){
        if ($this->request->isAjax()) {
            $key = input('key')?input('key'):'';
            $sotre_id = input('sotre_id');
            if(!empty($sotre_id)){
                $where['store_id'] = $sotre_id;
            }

            if(is_numeric(input('shelves')) === true){
                $where['shelves'] = input('shelves');
            }

            $where['name|cost|detection|money|material|stone|food|inch|weight|stone_number|stone_type|cleanliness|color|stone_weight|main_stones|goods_stone_shape|auxiliary_stone_weight|number_of_auxiliary_stones'] = array('like','%'.trim($key).'%');
            $list = GoodsModel::with('store')->field('goods_id,name,store_id,sort,method,shelves,sale_type,thumbnail_img,recommend')->order('sort desc,goods_id desc')->where($where)->paginate(input('limit'))->toArray();

            $url = config('aliyun_oss.url');

            foreach($list['data'] as $key =>$val)
            {
                $list['data'][$key]['thumbnail_img'] = str_replace("/goods",$url."goods",$val['thumbnail_img']);
            }

            return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);
        }


        $store = $this->store->store_();
        return view('list',['store'=>$store['data']]);
    }

    function add(){
        if(request()->isPost()){
            $data = $this->request->post();
            $data['details'] = base64_decode($data['details']);

            if($data['thumbnail_img']=='' ||empty($data['focus_img'])){
                return json(array('code' => 0, 'msg' => '请上传图片'));
            }

            $url = config('aliyun_oss.url');

            $data['thumbnail_img'] = str_replace($url."goods","/goods",$data['thumbnail_img']);

            $data['focus_img'] = implode(",",$data['focus_img']);
            $data['focus_img'] = str_replace($url."goods","/goods",$data['focus_img']);
            $data['details'] = judgeHtml(str_replace($url."goods","/goods",$data['details']));



            if($data['mode']==0){
                $barcodes = explode(",",$data['barcodes']);
                if(count($barcodes)!=$data['store']){
                    return json(array('code'=>0,'msg'=>'库存和条形码数量不一样'));
                }
                $data['large'] = $data['price'];
                $data['small'] = $data['price'];
            }else{
                foreach ($data['item'] as $k=>$item){
                    $barcodes = explode(",",$item['barcodes']);
                    if(count($barcodes)!=$item['store']){
                        return json(array('code'=>0,'msg'=>'库存和条形码数量不一样'));
                    }
                }
                $godos_m = array_column($data['item'],"price");
                $data['large'] = max($godos_m);
                $data['small'] = min($godos_m);
                unset($godos_m);
            }

            if(count($data['delivery'])==2){
                $data['delivery'] = 0;
            }else{
                if(empty($data['delivery'][0])){
                    $data['delivery'] = 2;
                }else{
                    $data['delivery'] = 1;
                }
            }

            if($data['mode']==0){
                $data['type_id'] = 0;
            }

            $this->model->startTrans();
            $this->SpecGoodsPrice->startTrans();
            $this->goods_label->startTrans();
            $this->code->startTrans();

            try{
                $goodsid = $this->model->add($data);
                //商品标签
                $label = implode(",",$data['label']);
                if(empty($label)){
                    return json(array('code'=>0,'msg'=>'添加失败，请选择标签'));
                }

                $goodslabel['goods_id'] = $goodsid;
                $goodslabel['label_id'] = $label;

                $this->goods_label->add($goodslabel);

                if($data['mode']==0) {
                    $data['goods_id'] = $goodsid;
                    $price_id = $this->SpecGoodsPrice->add($data);
                }else{
                    foreach ($data['item'] as $k=>$v){
                        $v['goods_id'] = $goodsid;
                        $v['price_key'] = $k;
                        $bracode = $v['barcodes'];
                        unset($v['barcodes']);
                        $specprice_id = SpecGoodsPrice::create($v);
                        $price_id = $specprice_id->price_id;
                        $barcodes = explode(",",$bracode);
                        foreach ($barcodes as $ke=>$item){
                            $barc[$ke]['barcodes'] = $item;
                            $barc[$ke]['price_id'] = $price_id;
                        }

                        $this->code->saveAll($barc);
                        unset($price_id);
                    }

                }
                if($data['mode']==0) {
                    //激活码
                    foreach ($barcodes as $key => $val) {
                        $goodscode[$key]['price_id'] = $price_id;
                        $goodscode[$key]['barcodes'] = $val;
                    }
                    $goodsid = $this->code->saveAll($goodscode);
                }

                $this->model->commit();
                $this->SpecGoodsPrice->commit();
                $this->goods_label->commit();
                $this->code->commit();
                return json(array('code'=>200,'msg'=>'添加成功'));
            }catch(\Exception $e){
                $this->model->rollback();
                $this->SpecGoodsPrice->rollback();
                $this->goods_label->rollback();
                $this->code->rollback();
                return json(array('code'=>0,'msg'=>'添加失败'));
            }

        }



        $label = Db::name('label')->select();
        foreach ($label as $key=>$val){
            if($val['parent_id']==0){
                $label2[$key] = $val;
                unset($label[$key]);
            }
            foreach ($label2 as $k=>$v){
                if($val['parent_id']==$v['label_id']){
                    $label2[$k]['names'][$key] = $val;
                }
            }
        }

        $Materiel = Db::name('materiel')->where('parent_id = 0')->select();
        $goods_type = Db::name('goods_type')->select();
        $store = Db::name('store')->select();
        return view('add',['label'=>$label2,'materiel'=>$Materiel,'goods_type'=>$goods_type,'store'=>$store]);
    }



    function edit(){
        if(request()->isPost()) {
            $data = $this->request->post();
            $data['details'] = base64_decode($data['details']);

            if($data['thumbnail_img']=='' ||empty($data['focus_img'])){
                return json(array('code' => 0, 'msg' => '请上传图片'));
            }

            $url = config('aliyun_oss.url');

            $data['thumbnail_img'] = str_replace($url."goods","/goods",$data['thumbnail_img']);

            $data['focus_img'] = implode(",",$data['focus_img']);
            $data['focus_img'] = str_replace($url."goods","/goods",$data['focus_img']);
            $data['details'] = judgeHtml(str_replace($url."goods","/goods",$data['details']));

            if ($data['mode'] == 0) {
                $data['type_id'] = 0;
                unset($data['item']);
                $barcodes = explode(",", $data['barcodes']);
                if (count($barcodes) != $data['store']) {
                    return json(array('code' => 0, 'msg' => '库存和条形码数量不一样'));
                }
                $data['large'] = $data['price'];
                $data['small'] = $data['price'];
            } else {
                foreach ($data['item'] as $k => $item) {
                    $barcodes = explode(",", $item['barcodes']);
                    if (count($barcodes) != $item['store']) {
                        return json(array('code' => 0, 'msg' => '库存和条形码数量不一样'));
                    }
                }
                $godos_m = array_column($data['item'],"price");
                $data['large'] = max($godos_m);
                $data['small'] = min($godos_m);
                unset($godos_m);
            }

            if (count($data['delivery']) == 2) {
                $data['delivery'] = 0;
            } else {
                if (empty($data['delivery'][0])) {
                    $data['delivery'] = 2;
                } else {
                    $data['delivery'] = 1;
                }
            }


            $this->model->startTrans();
            $this->SpecGoodsPrice->startTrans();
            $this->goods_label->startTrans();
            $this->code->startTrans();

            try {
                if(empty($data['label'])){
                    return json(array('code' => 0, 'msg' => '添加失败，标签为空'));
                }

                //商品标签//查询是否存在,切割成字符串
                $data['label_id'] = implode(",",$data['label']);
                unset($data['label']);
                $goods_label_id = Db::name('goods_label')->where("goods_id={$data['goods_id']}")->field('goods_label_id')->find();
                $data['goods_label_id'] = $goods_label_id['goods_label_id'];
                $result = $this->goods_label->edit($data);
                $result = $this->model->edit($data);


            if ($data['mode'] == 0) {
                $spec_goods_price = Db::name("spec_goods_price")->where("goods_id={$data['goods_id']}")->find();
                if ($spec_goods_price['price_key'] != 0) {
                    $result = $this->SpecGoodsPrice->destroy(['goods_id' => $data['goods_id']]);
                    $price_id = $this->SpecGoodsPrice->add($data);
                    $codeMap['price_id'] = $spec_goods_price['price_id'];
                    $codeMap['state'] = 0;
                    $codeMap['update_time'] = array('null',null);
                    $this->code->destroy($codeMap);
                    foreach ($barcodes as $key => $val) {
                        $goodscode[$key]['price_id'] = $price_id;
                        $goodscode[$key]['barcodes'] = $val;
                    }
                    $goodsid = $this->code->saveAll($goodscode);

                } else {
                    if(!$spec_goods_price['price_id']){
                        $priceId = $this->SpecGoodsPrice->add($data);
                        $data['price_id'] = $priceId;
                        $spec_goods_price['price_id'] = $priceId;
                    }else{
                        $data['price_id'] = $spec_goods_price['price_id'];
                        $this->SpecGoodsPrice->edit($data);
                    }

                    $coode_bracode = implode(",",$barcodes);
                    $where['barcodes'] = array('not in',$coode_bracode);
                    $where['price_id'] = $spec_goods_price['price_id'];
                    $codeid = Db::name('code')->where($where)->select();
                    if($codeid){
                        foreach ($codeid as $k => $item) {
                            $codeMap['code_id'] = $item['price_id'];
                            $codeMap['state'] = 0;
                            $codeMap['update_time'] = array('null',null);
                            $this->code->destroy($codeMap);
                        }
                    }
                    foreach ($barcodes as $key => $val) {
                        $codedata['price_id'] = $spec_goods_price['price_id'];
                        $codedata['barcodes'] = $val;
                        $code_i = Db::name('code')->where($codedata)->find();
                        if(!$code_i){
                            $result = $this->code->add($codedata);
                        }
                    }
                }
            } else {
                $id = $data['goods_id'];
                $specStock = Db::name('spec_goods_price')->where('goods_id = '.$data['goods_id'])->column('price_key');
                if(empty($specStock[0])){
                    $this->SpecGoodsPrice->destroy(['goods_id'=>$id]);
                    $price_id = Db::name('spec_goods_price')->field('price_id')->where('goods_id = '.$data['goods_id'])->find();
                    $codeMap['price_id'] = $price_id['price_id'];
                    $codeMap['state'] = 0;
                    $codeMap['update_time'] = array('null',null);
                    $this->code->destroy($codeMap);
                }
                foreach ($specStock as $key=>$time){
                    if(!empty($time)){
                        $specStocks[$time] = $time;
                    }
                }

                if ($data['item']) {
                    $keyArr = '';//规格key数组
                    foreach ($data['item'] as $k => $v) {
                        if($v['price']==0){
                            return json(array('code' => 0, 'msg' => '操作失败,价格不能为0'));
                        }

                        $keyArr .= $k.',';
                        // 批量添加数据
                        $v['price'] = trim($v['price']);
                        $v['cost_price'] = trim($v['cost_price']);
                        $v['settlement_price'] = trim($v['settlement_price']);
                        $v['store'] = trim($v['store']);
                        $v['store'] = trim($v['store']);
                        $v['market_price'] = trim($v['market_price']);
                        $v['deposit'] = trim($v['deposit']);
                        $v['rent'] = trim($v['rent']);
                        $v['settlement'] = trim($v['settlement']);
                        $data1 = ['goods_id' => $id,'deposit'=>$v['deposit'],'rent'=>$v['rent'],'settlement'=>$v['settlement'],'market_price'=>$v['market_price'],'store' => $v['store'], 'price_key' => $k, 'price_key_name' => $v['price_key_name'], 'price' => $v['price'], 'cost_price' => $v['cost_price'],'price' => $v['price'], 'settlement_price' => $v['settlement_price']];


                        if (!empty($specStocks[$k])) {
                            Db::table('je_spec_goods_price') ->where(['goods_id' => $id, 'price_key' => $k])->update($data1);
                        } else {
                            $price_id = $this->SpecGoodsPrice->add($data1);
                        }
                        $price = Db::name('spec_goods_price')->where("goods_id={$id} and price_key={$k}")->find();

                        $coode_bracode1 = implode(",",$v['barcodes']);
                        $where1['barcodes'] = array('not in',$coode_bracode1);
                        $where1['price_id'] = $price['price_id'];

                        $codeid = Db::name('code')->where($where1)->select();
                        if($codeid){
                            foreach ($codeid as $k => $item) {
                                $codeMap['code_id'] = $item['code_id'];
                                $codeMap['state'] = 0;
                                $codeMap['update_time'] = array('null',null);
                                $this->code->destroy($codeMap);
                            }
                        }
                        $barcodes = explode(",",$v['barcodes']);
                        foreach ($barcodes as $key => $val) {
                            $codedata1['price_id'] = $price['price_id'];
                            $codedata1['barcodes'] = $val;
                            $code_i = Db::name('code')->where($codedata1)->find();
                            if(!$code_i){
                                $result = $this->code->add($codedata1);
                            }
                        }

                    }

                    $map['price_key'] =array('not in',$keyArr);
                    $map['goods_id'] = $id;
                    $this->SpecGoodsPrice->destroy($map);

                }else{
                    $map['goods_id'] = $id;
                    $this->SpecGoodsPrice->destroy($map);
                }

            }

                $this->model->commit();
                $this->SpecGoodsPrice->commit();
                $this->goods_label->commit();
                $this->code->commit();
                return json(array('code' => 200, 'msg' => '添加成功'));

            }catch(\Exception $e){
                $this->model->rollback();
                $this->SpecGoodsPrice->rollback();
                $this->goods_label->rollback();
                $this->code->rollback();
                return json(array('code' => 0, 'msg' => '添加失败'));
            }
        }



        $label = Db::name('label')->select();
        foreach ($label as $key=>$val){
            if($val['parent_id']==0){
                $label2[$key] = $val;
                unset($label[$key]);
            }
            foreach ($label2 as $k=>$v){
                if($val['parent_id']==$v['label_id']){
                    $label2[$k]['names'][$key] = $val;
                }
            }
        }
        $Materiel = Db::name('materiel')->select();
        foreach ($Materiel as $key=>$val){
            if($val['parent_id']==0){
                $Materiel2[$key] = $val;
                unset($Materiel[$key]);
            }
            foreach ($Materiel2 as $k=>$v){
                if($val['parent_id']==$v['materiel_id']){
                    $Materiel2[$k]['names'][$key] = $val;
                }
            }
        }
        $goods_type = Db::name('goods_type')->select();
        $list = $this->model->where('goods_id',input('id'))->find();
        $goods_lable = Db::name('goods_label')->where('goods_id',input('id'))->find();
        $goodsLable = explode(",",$goods_lable['label_id']);
        foreach ($goodsLable as $k=>$t){
            $goodsLable2[$k]['label_id'] = $t;
        }

        $store = Db::name('store')->select();
        $spec_goods_price = Db::name('spec_goods_price')->where('goods_id',input('id'))->find();
        $code = Db::name('code')->where(['price_id'=>$spec_goods_price['price_id'],'state'=>0])->select();
        $code['barcodes'] = array_column($code,'barcodes');
        $spec_goods_price['barcodes'] = implode(",",$code['barcodes']);

        $list = $list->toArray();

        $url = config('aliyun_oss.url');

        $list['thumbnail_img'] = str_replace("/goods",$url."goods",$list['thumbnail_img']);
        $list['focus_img'] = str_replace("/goods",$url."goods",$list['focus_img']);
        $list['focus_img'] = explode(',', $list['focus_img']);

        $list['details'] = str_replace("/goods",$url."goods",$list['details']);

        $materiel_id_code = Db::name('materiel')->where("materiel_id={$list['materiel_id']}")->field('parent_id,materiel_id')->find();

        if($materiel_id_code['parent_id']!=0){
            $materiel_id_ = Db::name('materiel')->where("materiel_id={$materiel_id_code['parent_id']}")->field('parent_id,materiel_id')->find();

            $list['materiel_id_s'] = $materiel_id_['materiel_id'];
        }else{
            $list['materiel_id_s'] = $materiel_id_code['materiel_id'];
        }
        if($list['sale_type']==2){
            $lease = Db::name('spec_goods_price')->field('deposit,rent,settlement,price_key,price_key_name')->order('price_id asc')->where('goods_id',input('id'))->select();
        }else{
            $lease['price_key'] = '';
            $lease['deposit'] = '';
            $lease['rent'] = '';
            $lease['settlement'] = '';
        }

        return view('edit',['lease'=>$lease,'list'=>$list,'store'=>$store,'materiel'=>$Materiel2,'label'=>$label2,'goods_type'=>$goods_type,'goods_lable'=>$goodsLable2,'spec_goods_price'=>$spec_goods_price]);
    }



    //导入excel
    function import(){
        $params = input('post.');
        $filePath = ROOT_PATH.$params['path'];
        import('PHPExcel.PHPExcel', EXTEND_PATH);
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                return json(array('code'=>0,'msg'=>'格式无法识别'));
            }
        }
        $PHPExcel = $PHPReader->load($filePath);
        $currentSheet = $PHPExcel->getSheet(0); /*     * 读取excel文件中的第一个工作表 */
        $allRow = $currentSheet->getHighestRow(); /*     * 取得一共有多少行 */
        if ($allRow <= 1) {
            return json(array('code'=>0,'msg'=>'导入数据不存在'));
        };
        $l = $currentSheet->getHighestColumn();/*     * 取得一共有多少列 */
        $import_data = array();
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            if(empty($currentSheet->getCell('B' . $currentRow)->getValue())){
                continue;
            }
            if($currentSheet->getCell($l. $currentRow)->getValue()){
                $import_data = array(
                   // 'code_sn'             => $currentSheet->getCell('A' . $currentRow)->getValue(),
                    'name'             => $currentSheet->getCell('B' . $currentRow)->getValue(),
                    'method'             => $currentSheet->getCell('C' . $currentRow)->getValue(),
                    'method_value'             => $currentSheet->getCell('D' . $currentRow)->getValue(),
                    'cost'             => $currentSheet->getCell('E' . $currentRow)->getValue(),
                    'currency'             => $currentSheet->getCell('F' . $currentRow)->getValue(),
                    'thumbnail_img'             => $currentSheet->getCell('G' . $currentRow)->getValue(),
                    'focus_img'             => $currentSheet->getCell('H' . $currentRow)->getValue(),
                    'details'             => $currentSheet->getCell('I' . $currentRow)->getValue(),
                    'detection'             => $currentSheet->getCell('J' . $currentRow)->getValue(),
                    'money'             => $currentSheet->getCell('K' . $currentRow)->getValue(),
                    'material'             => $currentSheet->getCell('L' . $currentRow)->getValue(),
                    'stone'             => $currentSheet->getCell('M' . $currentRow)->getValue(),
                    'food'             => $currentSheet->getCell('N' . $currentRow)->getValue(),
                    'inch'             => $currentSheet->getCell('O' . $currentRow)->getValue(),
                    'weight'             => $currentSheet->getCell('P' . $currentRow)->getValue(),
                    'stone_number'             => $currentSheet->getCell('Q' . $currentRow)->getValue(),
                    'stone_shape'             => $currentSheet->getCell('R' . $currentRow)->getValue(),
                    'cleanliness'             => $currentSheet->getCell('S' . $currentRow)->getValue(),
                    'color'             => $currentSheet->getCell('T' . $currentRow)->getValue(),
                    'stone_weight'             => $currentSheet->getCell('U' . $currentRow)->getValue(),
                    'main_stones'             => $currentSheet->getCell('V' . $currentRow)->getValue(),
                    'goods_stone_shape'             => $currentSheet->getCell('W' . $currentRow)->getValue(),
                    'auxiliary_stone_weight'             => $currentSheet->getCell('X' . $currentRow)->getValue(),
                    'number_of_auxiliary_stones'             => $currentSheet->getCell('Y' . $currentRow)->getValue(),
                    'store_id'             => $currentSheet->getCell('Z' . $currentRow)->getValue(),
                    'discount'             => $currentSheet->getCell('AA' . $currentRow)->getValue(),
                    'delivery'             => $currentSheet->getCell('AB' . $currentRow)->getValue(),
                    'label_id'             => $currentSheet->getCell('AC' . $currentRow)->getValue(),
                    'materiel_id'             => $currentSheet->getCell('AD' . $currentRow)->getValue(),
                    'market_price'             => $currentSheet->getCell('AE' . $currentRow)->getValue(),
                     'price'             => $currentSheet->getCell('AF' . $currentRow)->getValue(),
                    'cost_price'             => $currentSheet->getCell('AG' . $currentRow)->getValue(),
                    'settlement_price'             => $currentSheet->getCell('AH' . $currentRow)->getValue(),
                    'store'             => $currentSheet->getCell('AI' . $currentRow)->getValue(),
                    'barcodes'             => $currentSheet->getCell('AJ' . $currentRow)->getValue(),
                );
            }


                $this->model->startTrans();
                $this->SpecGoodsPrice->startTrans();
                $this->goods_label->startTrans();
                $this->code->startTrans();

                $barcodes = explode(",",$import_data['barcodes']);
                if(count($barcodes)!=$import_data['store']){
                    return json(array('code'=>0,'msg'=>'库存和条形码数量不一样'));
                }
                   if(empty($import_data['method_value'])){
                       $import_data['method_value'] = 0;
                   }if(empty($import_data['cost'])){
                       $import_data['cost'] = 0;
                   }if(empty($import_data['currency'])){
                       $import_data['currency'] = 0;
                   }
                try{
                    $materiel_id = Db::name("materiel")->field('materiel_id')->where("code='{$import_data['materiel_id']}'")->find();
                    $import_data['materiel_id'] = $materiel_id['materiel_id'];
                    $import_data['large'] = $import_data['price'];
                    $import_data['small'] = $import_data['price'];
                    $goods_id = $this->model->add($import_data);
                    $label = explode("，",$import_data['label_id']);
                    foreach ($label as $key=>$item){
                        $label_id = Db::name("label")->field('label_id')->where("name='$item'")->find();
                        $goodsLabel[$key]['label_id'] = $label_id['label_id'];
                    }
                    $label = array_column($goodsLabel,'label_id');
                    unset($goodsLabel);
                    $goods_label = implode(",",$label);
                    $goodslabe['goods_id'] = $goods_id;
                    $goodslabe['label_id'] = $goods_label;
                    $this->goods_label->add($goodslabe);

                    $import_data['goods_id'] = $goods_id;
                    $price = $this->SpecGoodsPrice->add($import_data);

                    foreach ($barcodes as  $k=>$v){
                        $goodscode[$k]['barcodes'] = $v;
                        $goodscode[$k]['price_id'] = $price;
                    }
                    $this->code->saveAll($goodscode);
                    $this->model->commit();
                    $this->SpecGoodsPrice->commit();
                    $this->goods_label->commit();
                    $this->code->commit();

                }catch(\Exception $e){
                    $this->model->rollback();
                    $this->SpecGoodsPrice->rollback();
                    $this->goods_label->rollback();
                    $this->code->rollback();
                    return json(array('code'=>0,'msg'=>'导入失败，'.【.$import_data['name'].】没有成功));
                }


        }
        @unlink($filePath);
        return json(array('code'=>200,'msg'=>'导入成功'));
    }


        //更新一口价商品
        function save_yikongjia(){
             $jj = input('jj');

            //拿到系统配置信息
            $value = Db::name('config')->select();
            foreach ($value as $rs){
                $config[$rs['name']] = $rs['value'];
            }

            if($config['jingjia']!= $jj){
                return json(array('code'=>0,'msg'=>'请先保存后进行更新'));
            }

            $this->SpecGoodsPrice->startTrans();
            $goods_list = Db::name('goods')->field('goods_id,cost,method_value,materiel_id')->where('mode = 0')->select();


            try{
                foreach($goods_list as $key=>$val){
                    //销售价
                    $data['price'] = $val['method_value']*($config['jingjia']+$val['cost']);
                    //物料
                    $materiel = Db::name('materiel')->where("materiel_id = {$val['materiel_id']}")->find();

                    if($materiel['value_x']<1 && $materiel['value_y']<1 && $materiel['value_z']<1){
                        $materiel = Db::name('materiel')->where("materiel_id={$materiel['parent_id']}")->find();
                        if($materiel['value_x']<1 && $materiel['value_y']<1 && $materiel['value_z']<1){
                            $materiel['value_x'] = $config['x'];
                            $materiel['value_y'] = $config['y'];
                            $materiel['value_z'] = $config['z'];
                        }
                    }
                    $goods_price = Db::name('spec_goods_price')->where("goods_id = {$val['goods_id']}")->field('price_id,cost_price')->find();
                    $data['settlement_price'] = (($data['price'] * $materiel['value_x'])/100)+$goods_price['cost_price'] *  $materiel['value_y'] + $materiel['value_z'];
                    $data['price_id'] = $goods_price['price_id'];

                    $retule = $this->SpecGoodsPrice->edit($data);

                    $this->SpecGoodsPrice->commit();
                }
            }catch(\Exception $e){
                $this->SpecGoodsPrice->rollback();
                return json(array('code'=>0,'msg'=>"更改失败，名称为【{$val['name']}】的数据价格更新失败"));
            }
            return json(array('code'=>200,'msg'=>"更新成功"));
        }


    function del(){
        $where['goods_id'] = input('goods_id');
        $order_goods_name = Db::name('order_goods')->where($where)->find();
        if($order_goods_name){
            return json(array('code'=>0,'msg'=>'删除失败，已有购买订单，不能被删除'));
        }
        $this->model->startTrans();
        $this->SpecGoodsPrice->startTrans();
        $this->goods_label->startTrans();
        $this->code->startTrans();
        try{
            $this->model->destroy(input('goods_id'));
            $goods_price = Db::name('spec_goods_price')->where($where)->field('price_id')->select();
            //$price_id = $this->SpecGoodsPrice->where($where)->find()->toArray();
            $this->SpecGoodsPrice->destroy($where);
            $this->goods_label->destroy($where);
            foreach ($goods_price as $key=>$itme){
                $this->code->destroy(['price_id'=>$itme['price_id']]);
            }
            $this->model->commit();
            $this->SpecGoodsPrice->commit();
            $this->goods_label->commit();
            $this->code->commit();
            return json(array('code'=>200,'msg'=>'删除成功'));
        }catch(\Exception $e){
            $this->model->rollback();
            $this->SpecGoodsPrice->rollback();
            $this->goods_label->rollback();
            $this->code->rollback();
            return json(array('code'=>0,'msg'=>'删除失败'));
        }
    }

    function delete(){
        $params = input('post.');
        $ids = implode(',', $params['goods_id']);
        $this->model->dele($ids);
        $result = $this->model->batches('delete',$ids);
        if($result){
            return json(array('code'=>200,'msg'=>'批量删除成功'));
        }else{
            return json(array('code'=>0,'msg'=>'批量删除失败'));
        }

    }


    function displays(){
        $params = input('get.');
        $result = $this->model->changeTableVal($params);
        if($result){
            return json(array('code'=>200,'msg'=>'操作成功'));
        }else{
            return json(array('code'=>0,'msg'=>'操作失败'));
        }

    }


    //物料加载
    function wuliao(){
        $materiel_parent = Db::name('materiel')->field('materiel_id,name')->where('parent_id', input('id'))->select();
        if(empty($materiel_parent)){
            echo '';die;
        }
        $str = "<select style=\"width:8%;margin-left:15px\" name=\"materiel_id\" id=\"materiel_id\" lay-filter=\"selectwuliao\">";
        foreach ($materiel_parent as $k => $v)
        {
            if(input('m_id')==$v['materiel_id']){
                $str .="<option value=".$v['materiel_id']." selected=\"selected\" >".$v['name']."</option>";
            }else{
                $str .="<option value=".$v['materiel_id']." >".$v['name']."</option>";
            }
        }
        $str .="</select>";
        echo  $str;die;
    }




    //货重值
    function kuzhongzi(){
        $str = '';
        $str .='<label for="method_value" class="layui-form-label"><span class="x-red">*</span>货重值</label>';
        $str .='<div class="layui-input-inline"><input type="text" id="method_value" value="" name="method_value" required="" lay-verify="required" autocomplete="off" class="layui-input"></div>';
        $str .='<div class="layui-form-mid layui-word-aux"><span class="x-red">*请填写这框的值，不填不会计算价格</span></div>';
        echo  $str;die;
    }


    //工费
    function gongfei(){
        $str = '';
        $str .='<label for="cost" class="layui-form-label"><span class="x-red">*</span>工费</label>';
        $str .='<div class="layui-input-inline"><input type="text" id="cost" value="" name="cost" required="" lay-verify="required" autocomplete="off" class="layui-input"></div>';
        $str .='<div class="layui-form-mid layui-word-aux"><span class="x-red">*请填写这框的值，不填不会计算价格</span></div>';
        echo  $str;die;
    }




    //计算销售价
    function jisuan(){
        $wu_id = input('id');
        $kz = input('kz');
        $gf = input('gf');
        $jingjia = Db::name('config')->where("type='j'")->find();
        echo  $kz *($jingjia['value']+$gf);die;
    }

    //计算结算价
    function jisuan2(){
        $materiel_id = input('materiel_id');
        $xiaoshou = input('xiaoshou');
        $cost_price = input('cost_price');

        $materiel = Db::name('materiel')->where("materiel_id=$materiel_id")->find();
        if(empty($materiel['value_x']) && empty($materiel['value_y']) && empty($materiel['value_z'])){
            $materiel = Db::name('materiel')->where("materiel_id={$materiel['parent_id']}")->find();
            if(empty($materiel['value_x']) && empty($materiel['value_y']) && empty($materiel['value_z'])){
                $value = Db::name('config')->where("type='t'")->select();
                foreach ($value as $rs){
                    $config_qs[$rs['name']] = $rs['value'];
                }
                echo ($xiaoshou * $config_qs['x']/100) + $cost_price * $config_qs['y'] + $config_qs['z'];die;
            }
        }else{
            $value = Db::name('config')->where("type='t'")->select();
            foreach ($value as $rs){
                $config_qs[$rs['name']] = $rs['value'];
            }
            echo ($xiaoshou * $config_qs['x']/100) + $cost_price * $config_qs['y'] + $config_qs['z'];die;
        }

        echo ($xiaoshou * $materiel['value_x']/100) + $cost_price * $materiel['value_y'] + $materiel['value_z'];die;
    }



    //计算租赁
    function zulin(){
        $materiel_id = input('materiel_id');
        $price = input('price');
        $materiel = Db::name('materiel')->field('deposit,rent,settlement')->where("materiel_id=$materiel_id")->find();
        if(empty($materiel['deposit']) && empty($materiel['rent']) && empty($materiel['settlement'])){
            $materiel = Db::name('materiel')->field('deposit,rent,settlement')->where("materiel_id={$materiel['parent_id']}")->find();
        }
        $deposit = $price*$materiel['deposit'];
        $rent = $deposit/$materiel['rent'];
        $settlement = $deposit/$materiel['settlement'];


        if(input('item')){
            $item = input('item');

            $spec_item = db('spec_item')
                ->alias('i')
                ->join('spec s','i.spec_id = s.spec_id')
                ->field('s.name ,spec_item')
                ->where("item_id={$item}")->find();
            $spec_item = implode(":",$spec_item);

            $j = '';
            $j .= '<table class="table table-bordered" id="'.$item.'">';
            $j .= '<tr><td>押金</td><td>租金</td><td>商家结算</td></tr>';
            $j .='<tr><td style="border: 0;">'.$spec_item.'</td></tr>';
            $j .='<tr><td><input type="number" name="item['.$item.'][deposit]" value="'.$deposit.'"/></td><td><input type="number" name="item['.$item.'][rent]" value="'.$rent.'"/></td><td><input type="number" name="item['.$item.'][settlement]" value="'.$settlement.'"/></td></tr>';
            $j .= '</table>';
        }else{
            $j = '';
            $j .= '<table class="table table-bordered">';
            $j .= '<tr><td>押金</td><td>租金</td><td>商家结算</td></tr>';
            $j .='<tr><td><input type="number" name="deposit" value="'.$deposit.'"/></td><td><input type="number" name="rent" value="'.$rent.'"/></td><td><input type="number" name="settlement" value="'.$settlement.'"/></td></tr>';
            $j .= '</table>';
        }
        echo $j;die;
    }



    //秒杀商品
    function seckill(){
        $spec = input('g');
        $goods = Db::name('spec_goods_price')->field('price_key,price_key_name,store,price')->where('goods_id', input('id'))->select();

        $str = "<select style=\"width:8%;margin-left:15px\" name=\"spec_item\" id=\"spec_item\">";
        foreach ($goods as $k => $v)
        {   $price = $v['price'];
            $store = $v['store'];
            if($v['price_key']==0){
                $str .='<option value="0">无,'."$price".','."$store".'</option>';
            }else{
                if(!empty($spec) && $v['price_key']==$spec){
                    $str .="<option value=".$v['price_key']." selected>".$v['price_key_name'].",".$price.",".$store."</option>";
                }else{
                    $str .="<option value=".$v['price_key']." >".$v['price_key_name'].",".$price.",".$store."</option>";
                }
            }
        }
        $str .="</select>";
        echo  $str;die;
    }


        //主题商品选择
        function themegoods(){
            if ($this->request->isAjax()) {
                $key = input('key')?input('key'):'';
                if(is_numeric(input('state')) === true){
                    $where['g.sale_type'] = input('state');
                }if(is_numeric(input('type')) === true){
                    $where['g.store_id'] = input('type');
                }
                $where['g.name'] = array('like','%'.trim($key).'%');
                $list = Db::table('je_goods')->alias('g')->join('je_store s','g.store_id = s.store_id')->field('s.name as sname,g.name,g.thumbnail_img as img,g.large,g.sale_type,g.goods_id')->where($where)->order('g.sort desc ,g.goods_id desc')->paginate(input('limit'))->toArray();
                foreach ($list['data'] as $key=>$itme){
                    try{
                        $label = db('goods_label')->where("goods_id = {$itme['goods_id']}")->value('label_id');
                        $label = explode(',',$label);
                        foreach ($label as $k=>$v){
                            $name[] = db('label')->where("label_id = {$v}")->value('name');
                        }
                        $list['data'][$key]['label'] = implode(',',$name);  unset($name);

                    }catch(\Exception $e){

                    }
                    $list['data'][$key]['img'] = str_replace("/goods",config('aliyun_oss.url')."goods",$itme['img']);
                }
                return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);
            }

            $theme_id = input('id')?input('id'):0;
            if(empty($theme_id)) return json($result = ['code'=>0,'msg'=>'参数错误']);
            $info = db('store')->field('name,store_id')->select();
            return view('list2',['list'=>$info,'theme_id'=>$theme_id]);
        }



        /**
         * 动态获取商品规格选择框 根据不同的数据返回不同的选择框
         */
        function ajaxGetSpecSelect(){
        $goods_id = input('get.goods_id/d') ? input('get.goods_id/d') : 0;
        $specList = Db::name('spec')->where("type_id = ".input('get.type_id/d'))->select();
        foreach($specList as $k => $v)
            $specList[$k]['spec_item'] = Db::name('spec_item')->where("spec_id = ".$v['spec_id'])->order('item_id')->column('item_id,spec_item'); // 获取规格项
        $items_id = Db::name('spec_goods_price')->where('goods_id = '.$goods_id)->column("GROUP_CONCAT(`price_key` SEPARATOR '_') AS price_id");

        $items_ids = explode('_', $items_id[0]);




        $this->assign('items_ids',$items_ids);
        $this->assign('specList',$specList);
        return $this->fetch('ajax_spec_select');
    }

    /**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */
    public function ajaxGetSpecInput(){
        $goods_id = input('goods_id/d') ? input('goods_id/d') : 0;
        $str = $this->getSpecInput($goods_id ,input('post.spec_arr/a'));
        exit($str);
    }

    /**
     * 获取 规格的
     * @param $goods_id 商品 id
     * @param $spec_arr 笛卡尔积
     * @return string 返回表格字符串
     */
    public function getSpecInput($goods_id, $spec_arr)
    {   if(empty($spec_arr)){return '';}
        // 排序
        foreach ($spec_arr as $k => $v)
        {
            $spec_arr_sort[$k] = count($v);
        }
        asort($spec_arr_sort);
        foreach ($spec_arr_sort as $key =>$val)
        {
            $spec_arr2[$key] = $spec_arr[$key];
        }

        $clo_name = array_keys($spec_arr2);
        $spec_arr2 = combineDika($spec_arr2); //  获取 规格的

        $spec = Db::name('spec')->column('spec_id,name'); // 规格表
        $specItem = Db::name('spec_item')->column('item_id,spec_item,spec_id');//规格项
        $keySpecGoodsPrice = Db::name('spec_goods_price')->where('goods_id = '.$goods_id)->column('price_key,price_key_name,market_price,price,cost_price,settlement_price,store,price_id');//规格项

        foreach ($keySpecGoodsPrice as $ke=>$val){
            $code = Db::name('code')->where(['price_id'=>$val['price_id'],'state'=>0])->column('barcodes');//规格项
            $keySpecGoodsPrice[$ke]['barcodes'] = implode(",",$code);
        }

        $str = "<table class='table table-bordered' id='spec_input_tab'>";
        $str .="<tr>";
        // 显示第一行的数据
        foreach ($clo_name as $k => $v)
        {
            $str .=" <td><b>{$spec[$v]}</b></td>";
        }
        $str .="<td><b>销售价</b></td>
                <td><b>成本价</b></td>
                <td><b>结算价</b></td>
                <td><b>市场价</b></td>
                <td><b>库存</b></td>
                <td><b>条形码</b></td>
             </tr>";
        // 显示第二行开始

        foreach ($spec_arr2 as $k => $v)
        {
            $str .="<tr>";
            $item_key_name = array();
            foreach($v as $k2 => $v2)
            {
                $str .="<td>{$specItem[$v2]['spec_item']}</td>";
                $item_key_name[$v2] = $spec[$specItem[$v2]['spec_id']].':'.$specItem[$v2]['spec_item'];
            }
            ksort($item_key_name);
            $item_key = implode('_', array_keys($item_key_name));

            $item_name = implode(' ', $item_key_name);

            $keySpecGoodsPrice[$item_key]['price'] ? false : $keySpecGoodsPrice[$item_key]['price'] = 0; // 价格默认为0，销售价
            $keySpecGoodsPrice[$item_key]['cost_price'] ? false : $keySpecGoodsPrice[$item_key]['cost_price'] = 0; // 价格默认为0，结算价
            $keySpecGoodsPrice[$item_key]['settlement_price'] ? false : $keySpecGoodsPrice[$item_key]['settlement_price'] = 0; // 价格默认为0，成本价
            $keySpecGoodsPrice[$item_key]['market_price'] ? false : $keySpecGoodsPrice[$item_key]['market_price'] = 0; // 价格默认为0，市场价
            $keySpecGoodsPrice[$item_key]['store'] ? false : $keySpecGoodsPrice[$item_key]['store'] = 0; // 价格默认为0，成本价
            $keySpecGoodsPrice[$item_key]['barcodes'] ? false : $keySpecGoodsPrice[$item_key]['barcodes'] = 0; // 激活码
            $str .="<td><input id='ge' name='item[$item_key][price]' value='{$keySpecGoodsPrice[$item_key]['price']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' /></td>";
            $str .="<td><input name='item[$item_key][cost_price]' value='{$keySpecGoodsPrice[$item_key]['cost_price']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' /></td>";
            $str .="<td><input name='item[$item_key][settlement_price]' value='{$keySpecGoodsPrice[$item_key]['settlement_price']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' /></td>";
            $str .="<td><input name='item[$item_key][market_price]' value='{$keySpecGoodsPrice[$item_key]['market_price']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' /></td>";
            $str .="<td><input name='item[$item_key][store]' value='{$keySpecGoodsPrice[$item_key]['store']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' /></td>";
            $str .="<td><input name='item[$item_key][barcodes]' value='{$keySpecGoodsPrice[$item_key]['barcodes']}' type='text'  /></td>";
            $str .="<td><input type='hidden' name='item[$item_key][price_key_name]' value='$item_name' /></td>";

            $str .="</tr>";
        }
        $str .= "</table>";
        return $str;
    }

}